// 安装  mongoose

const mongoose = require("mongoose");

// 连接数据库       协议         地址          数据库
mongoose.connect("mongodb://127.0.0.1:27017/demo");

mongoose.connection.once("open", async () => {
  console.log("连接成功");

  // 设置 book 集合的 结构对象
  const bookSchema = mongoose.Schema({
    name: String,
    athor: String,
    price: Number,
  });

  // 创建 集合book 的一个模型 方便操作 集合
  const bookModel = mongoose.model("book", bookSchema);

  try {
    const result = await bookModel.create({
      name: "西游记",
      athor: "吴承恩",
      price: 19,
    });
    console.log("插入成功", result);
  } catch (e) {
    console.log("插入失败", e);
  }
});

mongoose.connection.once("error", () => {
  console.log("连接失败");
});

mongoose.connection.once("close", () => {
  console.log("连接关闭");
});

setTimeout(() => {
  mongoose.disconnect();
}, 3000);
